import { useState, useCallback } from 'react'
import { Dialog, DialogTitle, DialogContent, DialogContentText, DialogActions } from '@mui/material'
import { useTranslation } from 'react-i18next'
import ButtonStyled from './ButtonStyled'
import propTypes from 'prop-types'

const LocalDialog = (props) => {

  const { t, open, onClose, confirm, desc } = props

  return (
    <div>
      <Dialog
        open={open}
        onClose={onClose}
      >
        <DialogTitle>
          {t('common.tooltip')}
        </DialogTitle>
        <DialogContent sx={{ minWidth: '415px' }}>
          <DialogContentText>
            {desc ? desc : t('system.confirmRemove')}
          </DialogContentText>
        </DialogContent>
        <DialogActions>
          <ButtonStyled onClick={onClose}>{t('common.cancel')}</ButtonStyled>
          <ButtonStyled onClick={confirm}>{t('common.confirm')}</ButtonStyled>
        </DialogActions>
      </Dialog>
    </div>
  )
}

const ComfirmDialog = (props) => {

  const { t } = useTranslation()
  const { confirm, desc } = props

  const [open, setOpen] = useState(false)

  // 关闭弹窗
  const handleClose = useCallback(() => {
    setOpen(false)
  }, [])

  const handleOpen = useCallback((e) => {
    e.stopPropagation()
    e.preventDefault()
    setOpen(true)
  }, [])

  const submitDelete = useCallback(() => {
    if (confirm && typeof(confirm) === 'function') {
      confirm()
    }
    setOpen(false)
  }, [confirm])

  return (
    <div className={`MuiButton-root${props.className ? ' ' + props.className : ''}`} style={{ display: 'inline-flex', position: 'relative', ...props.style }}>
      <div onClick={(e) => handleOpen(e)}>
        {
          props.children ? props.children : (
            <ButtonStyled size="small" variant={props.variant} color="error">{t('common.delete')}</ButtonStyled>
          )
        }
      </div>
      <LocalDialog
        t={t}
        open={open}
        onClose={handleClose}
        confirm={submitDelete}
        desc={desc}
      >
      </LocalDialog>
    </div>
  )
}

ComfirmDialog.propTypes = {
  confirm: propTypes.func.isRequired,
  variant: propTypes.string,
  children: propTypes.node
}

ComfirmDialog.defaultProps = {
  variant: 'text'
}

export default ComfirmDialog